package com.telesound.dataimport;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.telesound.dataimport.excel.ExcelProcessor;
import com.telesound.dataimport.excel.XCell;
import com.telesound.dataimport.excel.XRow;
import com.telesound.dataimport.exception.CellContentTooLongException;
import com.telesound.dataimport.exception.ColumnRuleNotFoundException;
import com.telesound.dataimport.exception.CustomProduceMethodNotFoundException;
import com.telesound.dataimport.exception.DataImportException;
import com.telesound.dataimport.exception.DataLengthOutofBoundException;
import com.telesound.dataimport.exception.DataTypeNotMatchException;
import com.telesound.dataimport.exception.DateFormatNotFoundException;
import com.telesound.dataimport.exception.DicItemNotFoundException;
import com.telesound.dataimport.exception.EmptyDefaultValueException;
import com.telesound.dataimport.exception.ErrorDataListException;
import com.telesound.dataimport.exception.ExcelExistSameColumnException;
import com.telesound.dataimport.exception.FromListNotFoundException;
import com.telesound.dataimport.exception.NoValueOfDictionaryElementException;
import com.telesound.dataimport.exception.NullCellValueException;
import com.telesound.dataimport.exception.TableRuleNotFoundException;
import com.telesound.dataimport.util.StringUtil;
import com.telesound.dataimport.util.variable.DataTypeVariable;
import com.telesound.dataimport.util.variable.ProduceMethodVariable;


/**
 * Excel导入器，是整个Excel导入的核心类
 * @author zhangchaofeng
 * @version 1.0
 * @date Sep 28, 2011
 */
public class ExcelImporter{
	private String uuid;
	private String fileName;
	private int sheetIndex=-1;
	private ExcelProcessorThread p;
	private Thread processorThread;
	private DataImportTableRule tableRule; // 应用的导入表规则
	private boolean writeLog=false;
	private String loggerFile;
	private static Map<String,ExcelImporter> importerMap=new HashMap<String,ExcelImporter>();
	
	public ExcelImporter(String uuid,String fileName,String tableRuleId,boolean writeLog,String loggerFile) throws Exception {
		this.tableRule=DataImportTableRule.getTableRule(tableRuleId);
		if(this.tableRule==null){
			throw new TableRuleNotFoundException(tableRuleId);
		}
		this.uuid=uuid;
		this.fileName=fileName;
		this.writeLog=writeLog;
		this.loggerFile=loggerFile;
	}
	
	private Thread getProcessorThread(){
		return this.processorThread;
	}
	
	/**
	 * 导入所有sheet的数据
	 * @throws Exception
	 */
	public void importAllSheetData() throws Exception {
		this.sheetIndex=-1;
		ExcelProcessorThread thread=new ExcelProcessorThread(fileName);
		this.p=thread;
		this.processorThread=new Thread(thread);
		processorThread.start();
	}

	/**
	 * 导入指定sheet的数据
	 * @param sheetIndex
	 * @throws Exception
	 */
	public void importData(int sheetIndex) throws Exception {
		this.sheetIndex=sheetIndex;
		ExcelProcessorThread thread=new ExcelProcessorThread(fileName);
		this.p=thread;
		this.processorThread=new Thread(thread);
		processorThread.start();
	}
	
	/**
	 * 导入第一个sheet的数据
	 * @throws Exception
	 */
	public void importFirstSheetData() throws Exception {
		importData(1);
	}
	
	/**
	 * 暂停导入数据
	 * @throws InterruptedException
	 */
	public static void suspend(String uuid) throws InterruptedException{
		ExcelImporter importer=importerMap.get(uuid);
		if(importer!=null){
			//importer.processorThread.wait();
			importer.p.setRunFlag(false);
		}
	}
	
	/**
	 * 继续导入数据
	 */
	public static void resume(String uuid){
		ExcelImporter importer=importerMap.get(uuid);
		if(importer!=null){
			//importer.processorThread.notifyAll();
			importer.p.setRunFlag(true);
		}
	}
	
	/**
	 * 停止导入数据
	 */
	public static void stop(String uuid){
		ExcelImporter importer=importerMap.get(uuid);
		if(importer!=null){
			importer.processorThread.interrupt();
			try {
				importer.p.stop();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		importerMap.remove(uuid);
	}
	
	public static ImportResult getProcess(String uuid){
		ExcelImporter importer=importerMap.get(uuid);
		if(importer==null){
			return null;
		}
		ImportResult result=new ImportResult();
		ExcelProcessorThread pp=importer.p;
		result.setCorrentRow(pp.correntRowIndex+"");
		result.setFailed(pp.failedCount);
		result.setSuccess(pp.successCount);
		if(pp.complete){
			result.setComplete(true);
			result.setCorrentRow("结束");
			File excel=new File(importer.fileName);
			if(excel.exists()){
				excel.delete();
			}
		}
		return result;
	}
	
	public static String getProcessMessage(String uuid){
		ExcelImporter importer=importerMap.get(uuid);
		if(importer==null){
			return null;
		}
		List importMessages=importer.p.importMessages;
		StringBuffer message=new StringBuffer("");
		for(int i=0;i<importMessages.size();i++){
			message.append(importMessages.get(i)+"<br>");
		}
		return message.toString();
	}
	
	private class ExcelProcessorThread extends ExcelProcessor implements Runnable{
		private StringBuffer sql1=new StringBuffer("insert into "+tableRule.getTableName()+" (");
		private StringBuffer sql2=new StringBuffer(") values (");
		private String sql3=")";
		private int correntRowIndex=0;
		private int correntColumnIndex=0;
		private int successCount=0;
		private int failedCount=0;
		private boolean runFlag=true;
		private boolean complete=false;
		private Map<Integer,String> headerNames;
		private Map<String,String> columnValues;
		private Map<String,DataImportColumnRule> pkColumnRules;
		private List importMessages=new ArrayList();

		public ExcelProcessorThread(String fileName) throws Exception {
			super(fileName);
			this.headerNames=new HashMap<Integer,String>();
			this.columnValues=new HashMap<String,String>();
			this.pkColumnRules=new HashMap<String,DataImportColumnRule>();
		}
		
		public void setRunFlag(boolean b){
			this.runFlag=b;
		}
		
		/**
		 * 导入策略判断
		 * @param value
		 * @param columnRule
		 * @throws NullCellValueException 
		 * @throws DicItemNotFoundException 
		 * @throws NoValueOfDictionaryElementException 
		 * @throws CellContentTooLongException 
		 * @throws DataTypeNotMatchException 
		 * @throws EmptyDefaultValueException 
		 * @throws DataLengthOutofBoundException 
		 * @throws DateFormatNotFoundException 
		 * @throws CustomProduceMethodNotFoundException 
		 * @throws FromListNotFoundException 
		 * @throws ErrorDataListException 
		 */
		private void step(String value,DataImportColumnRule columnRule) throws DataTypeNotMatchException, CellContentTooLongException, NoValueOfDictionaryElementException, DicItemNotFoundException, NullCellValueException, EmptyDefaultValueException, DataLengthOutofBoundException, DateFormatNotFoundException, CustomProduceMethodNotFoundException, FromListNotFoundException, ErrorDataListException{
			String columnName=columnRule.getColumnName();
			String dataType=columnRule.getDataType();
			int maxLength=columnRule.getMaxLength();
			String method=columnRule.getProduceMethod();
			String produceMethodValue=columnRule.getProduceMethodValue();
			if(value!=null){
				value=value.trim();
			}
			//默认值时的处理策略
			if(ProduceMethodVariable.DEFAULT_VALUE.equals(method)){
				String defaultValue=columnRule.getProduceMethodValue().trim();
				if(!StringUtil.hasValue(defaultValue)){
					if(columnRule.getRequired()){
						throw new EmptyDefaultValueException("列规则生成策略为默认值，但实际默认值为空，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
					}
				}else{
					if(StringUtil.getStringLength(defaultValue)>maxLength){//长度过大
						throw new DataLengthOutofBoundException("默认值长度超过允许的最大长度，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
					}
					sql1.append(columnName+",");
					if(DataTypeVariable.DATE.equals(dataType)){//日期类型
						sql2.append("to_date("+defaultValue+",'yyyy-mm-dd hh24:mi:ss'),");
					}else if(DataTypeVariable.NUMBER.equals(dataType)){
						sql2.append(defaultValue+",");
					}else{
						sql2.append("'"+defaultValue+"',");
					}
					columnValues.put(columnName, defaultValue);
					
				}
			//导入数据时的处理策略
			}else if(ProduceMethodVariable.IMPORT_DATA.equals(method)){
				step1(value, columnRule);
			//自定义生成策略	
			}else if(ProduceMethodVariable.CUSTOM_METHOD.equals(method)){
				if(!StringUtil.hasValue(produceMethodValue)){
					throw new CustomProduceMethodNotFoundException("找不到对应的自定义生成策略类：["+produceMethodValue+"]，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
				}
				try {
					Class producor=Class.forName(produceMethodValue);
					Constructor con=producor.getConstructor(new Class[]{});
					Method meth=producor.getMethod("getPK", Object.class);
					Object obj=con.newInstance(new Object[]{});
					String pk=(String)meth.invoke(obj, columnValues);
					value=pk;
				} catch (Exception e) {
					e.printStackTrace();
				}
				//value=DBAccess.getUuid();
				step4(value, columnRule);
			}
		}
		
		/**
		 * 空值判断
		 * @param value
		 * @param columnRule
		 * @throws DicItemNotFoundException 
		 * @throws NoValueOfDictionaryElementException 
		 * @throws CellContentTooLongException 
		 * @throws DataTypeNotMatchException 
		 * @throws NullCellValueException 
		 * @throws DateFormatNotFoundException 
		 * @throws FromListNotFoundException 
		 * @throws ErrorDataListException 
		 */
		private void step1(String value,DataImportColumnRule columnRule) throws DataTypeNotMatchException, CellContentTooLongException, NoValueOfDictionaryElementException, DicItemNotFoundException, NullCellValueException, DateFormatNotFoundException, FromListNotFoundException, ErrorDataListException{
			if("".equals(value)&&columnRule.getRequired()){
				throw new NullCellValueException("规则显示该列不能为空，columnName："+columnRule.getColumnName()+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
			}else if(!"".equals(value)){
				step12(value, columnRule);
			}
		}
		
		/**
		 * 静态字典（数据来源于静态列表）判断
		 * @param value
		 * @param columnRule
		 * @throws DataTypeNotMatchException
		 * @throws CellContentTooLongException
		 * @throws NoValueOfDictionaryElementException
		 * @throws DicItemNotFoundException
		 * @throws DateFormatNotFoundException
		 * @throws FromListNotFoundException
		 * @throws ErrorDataListException
		 */
		private void step12(String value,DataImportColumnRule columnRule) throws DataTypeNotMatchException, CellContentTooLongException, NoValueOfDictionaryElementException, DicItemNotFoundException, DateFormatNotFoundException, FromListNotFoundException, ErrorDataListException{
			String columnName=columnRule.getColumnName();
			if(columnRule.getFromList()){
				String dataListStr=columnRule.getDataList();
				if(!StringUtil.hasValue(dataListStr)){
					throw new FromListNotFoundException("数据来源于列表，但未指定列表数据，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
				}
				Map<String,String> keyValueMap=new HashMap<String,String>();
				String[] dataArray=dataListStr.split(",");
				for(int i=0;i<dataArray.length;i++){
					String[] keyValue=dataArray[i].split("=");
					if(keyValue.length<2){
						throw new ErrorDataListException("数据来源列表格式错误，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
					}
					keyValueMap.put(keyValue[0], keyValue[1]);
				}
				String value1=keyValueMap.get(value);
				if(!StringUtil.hasValue(value1)){
					throw new ErrorDataListException("数据来源列表中无此数据："+value+"，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
				}
				step3(value1, columnRule);
			}else{
				step2(value, columnRule);
			}
		}
		
		/**
		 * 字典判断
		 * @param value
		 * @param columnRule
		 * @throws CellContentTooLongException 
		 * @throws DataTypeNotMatchException 
		 * @throws NoValueOfDictionaryElementException 
		 * @throws NoValueOfDictionaryElementException 
		 * @throws DicItemNotFoundException 
		 * @throws DateFormatNotFoundException 
		 */
		private void step2(String value,DataImportColumnRule columnRule) throws DataTypeNotMatchException, 
					CellContentTooLongException, NoValueOfDictionaryElementException, DicItemNotFoundException, DateFormatNotFoundException{
			String columnName=columnRule.getColumnName();
			if(columnRule.getIsDictionary()){
				String dicTableName=columnRule.getDicTableName();
				String dicTypeColumn=columnRule.getDicTypeColumn();
				String dicTypeValue=columnRule.getDicTypeValue();
				String dicReferenceColumn=columnRule.getDicReferenceColumn();
				String dicRequiredColumn=columnRule.getDicRequiredColumn();
				String dicCondition=columnRule.getDicCondition();
				if(!StringUtil.hasValue(dicTableName)){
					throw new NoValueOfDictionaryElementException("属于字典，却未指定字典表名称，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
				}
				if(!StringUtil.hasValue(dicReferenceColumn)){
					throw new NoValueOfDictionaryElementException("属于字典，却未指定字典参照列，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
				}
				if(!StringUtil.hasValue(dicRequiredColumn)){
					throw new NoValueOfDictionaryElementException("属于字典，却未指定字典区职务列，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
				}
				String sql="select "+dicRequiredColumn+" from "+dicTableName+" where "+dicReferenceColumn+"='"+value+"'";
				if(StringUtil.hasValue(dicTypeColumn)&&StringUtil.hasValue(dicTypeValue)){
					sql=sql+" and "+dicTypeColumn+"='"+dicTypeValue+"'";
				}
				if(StringUtil.hasValue(dicCondition)){
					sql=sql+" and "+dicCondition;
				}
				Map dicInfo=DBAccess.getSingleMap(sql, null);
				if(dicInfo==null||dicInfo.size()==0){
					throw new DicItemNotFoundException("找不到对应的字典项："+sql+"，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
				}else{
					Object obj=dicInfo.get(dicRequiredColumn.toLowerCase());
					step3(StringUtil.getStringValue(obj), columnRule);
				}
			}else{
				step3(value, columnRule);
			}
		}
		
		/**
		 * 唯一约束判断
		 * @param value
		 * @param columnRule
		 * @throws CellContentTooLongException 
		 * @throws DataTypeNotMatchException 
		 * @throws DateFormatNotFoundException 
		 * @throws DataImportException 
		 */
		private void step3(String value,DataImportColumnRule columnRule) throws DataTypeNotMatchException, CellContentTooLongException, DateFormatNotFoundException{
			boolean isUnique=columnRule.getIsUnique();
			String columnName=columnRule.getColumnName();
			String dataType=columnRule.getDataType();
			boolean deleteRepeat=tableRule.getDeleteRepeate();
			String tableName=tableRule.getTableName();
			if(!isUnique){
				step4(value, columnRule);
			}else{
				String sql="";
				if(DataTypeVariable.DATE.equals(dataType)){
					sql="select "+columnName+" from "+tableName+" where to_char("+columnName+",'yyyy-mm-dd')='"+value+"'";
				}else if(DataTypeVariable.NUMBER.equals(dataType)){
					sql="select "+columnName+" from "+tableName+" where "+columnName+"="+value;
				}else{
					sql="select "+columnName+" from "+tableName+" where "+columnName+"='"+value+"'";
				}
				Map info=DBAccess.getSingleMap(sql, null);
				if(info==null||info.size()==0){
					step4(value, columnRule);
				}else if(deleteRepeat){
					System.out.println("需要删除掉数据。。。。。。");
				}else{
					step4(value, columnRule);
				}
			}
		}
		
		/**
		 * 数据类型判断
		 * @param value
		 * @param columnRule
		 * @throws DataTypeNotMatchException 
		 * @throws CellContentTooLongException 
		 * @throws DateFormatNotFoundException 
		 */
		private void step4(String value,DataImportColumnRule columnRule) throws DataTypeNotMatchException, CellContentTooLongException, DateFormatNotFoundException{
			String dataType=columnRule.getDataType();
			String dateFormat=columnRule.getDateFormat();
			String columnName=columnRule.getColumnName();
			int maxLength=columnRule.getMaxLength();
			int valueLength=StringUtil.getStringLength(value);
			if(DataTypeVariable.DATE.equals(dataType)){
				if(dateFormat==null){
					throw new DateFormatNotFoundException("日期类型，但未配置对应的日期格式，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
				}
				sql1.append(columnName+",");
				sql2.append("to_date('"+value+"','"+dateFormat+"'),");
				columnValues.put(columnName, value);
			}else if(DataTypeVariable.NUMBER.equals(dataType)){
				if(!StringUtil.hasValue(value)){
					return;
				}
				if(!StringUtil.isNumber(value)){
					throw new DataTypeNotMatchException("数据类型不匹配，单元格中内容并非数字格式，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
				}else{
					if(value.contains(".")){
						int index=value.indexOf(".");
						int length=value.length();
						if((length-index-1)>5){
							value=value.substring(0,index+6);
						}
					}
					valueLength=StringUtil.getStringLength(value);
					if(maxLength<valueLength){
						throw new CellContentTooLongException("单元格内容过长，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
					}else{
						sql1.append(columnName+",");
						sql2.append(value+",");
						columnValues.put(columnName, value);
					}
				}
			}else{
				if(maxLength<valueLength){
					throw new CellContentTooLongException("单元格内容过长，columnName："+columnName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
				}else{
					sql1.append(columnName+",");
					sql2.append("'"+value+"',");
					columnValues.put(columnName, value);
				}
			}
		}

		@Override
		public void processRow(XRow row) {
			try {
				while(!runFlag){
					Thread.sleep(10);
				}
				Thread.sleep(10);
			} catch (InterruptedException e) {
				
			}
			/*for(int i=0;i<row.getCellsSize();i++){
				System.out.print("["+row.getRowIndex()+","+(char)row.getCell(i).getColumnIndex()+","+row.getCell(i).getValue()+"]");
			}
			System.out.println();*/
			correntRowIndex=row.getRowIndex();
			columnValues.clear();
			pkColumnRules.clear();
			sql1=new StringBuffer("insert into "+tableRule.getTableName()+" (");
			sql2=new StringBuffer(") values (");
			if(row.getRowIndex()==1){//标题行
				for(int i=0;i<row.getCellsSize();i++){
					XCell cell=row.getCell(i);
					String value=cell.getValue();
					headerNames.put(i, value);
				}
				importMessages.add("处理标题行，成功");
				if(writeLog){
					ImportLogger.writeLog(loggerFile, uuid, "处理标题行，成功");
				}
			}else{
				Map<String,XCell> rowData=new HashMap<String,XCell>();
				Map<String,DataImportColumnRule> columnRules=new HashMap<String,DataImportColumnRule>(tableRule.getColumnRules());
				try {
					for(int i=0;i<row.getCellsSize();i++){
						XCell cell=row.getCell(i);
						String headerName=(String)headerNames.get(i);
						if(!rowData.containsKey(headerName)){
							//将单元格值以标题为key放入map中，重复列则后面的忽略
							rowData.put(headerName, cell);
						}else{
							throw new ExcelExistSameColumnException("重复列，headerName："+headerName+"，后面的重复列将被忽略");
						}
					}
				}catch(ExcelExistSameColumnException e){
					e.printStackTrace();
					failedCount++;
					importMessages.add("处理第"+correntRowIndex+"行，失败，"+e.getMessage());
					if(writeLog){
						ImportLogger.writeLog(loggerFile, uuid, "处理第"+correntRowIndex+"行，失败，"+e.getMessage());
					}
				}
				
				//以Excel列为主导进行一次遍历操作
				Iterator<String> rowIt=rowData.keySet().iterator();
				while(rowIt.hasNext()){
					String headerName=rowIt.next();
					XCell cell=rowData.get(headerName);
					String value=cell.getValue();
					correntColumnIndex=cell.getColumnIndex();
					DataImportColumnRule columnRule=tableRule.getColumnRule(headerName);
					try {
						if(columnRule==null){
							throw new ColumnRuleNotFoundException("未找到指定的列规则，headerName："+headerName+"，"+correntRowIndex+"行，"+(char)correntColumnIndex+"列");
						}
						step(value, columnRule);
					} catch (DataImportException e) {
						e.printStackTrace();
						failedCount++;
						importMessages.add("处理第"+correntRowIndex+"行，失败，"+e.getMessage());
						if(writeLog){
							ImportLogger.writeLog(loggerFile, uuid, "处理第"+correntRowIndex+"行，失败，"+e.getMessage());
						}
						return;
					}
					columnRules.remove(headerName);
				}
					
				//以列规则为主导进行一次遍历操作，处理表中一些隐含字段
				Iterator<String> ruleIt=columnRules.keySet().iterator();
				while(ruleIt.hasNext()){
					String columnName=ruleIt.next();
					DataImportColumnRule columnRule=columnRules.get(columnName);
					if(columnRule.getIsPk()){
						pkColumnRules.put(columnName, columnRule);
						continue;
					}
					try {
						step("", columnRule);
					} catch (DataImportException e) {
						e.printStackTrace();
						failedCount++;
						importMessages.add("处理第"+correntRowIndex+"行，失败，"+e.getMessage());
						if(writeLog){
							ImportLogger.writeLog(loggerFile, uuid, "处理第"+correntRowIndex+"行，失败，"+e.getMessage());
						}
						return;
					}
				}
				
				//主键放到最后处理
				Iterator<String> pkColumnIt=pkColumnRules.keySet().iterator();
				while(pkColumnIt.hasNext()){
					String columnName=pkColumnIt.next();
					DataImportColumnRule columnRule=pkColumnRules.get(columnName);
					try {
						step("", columnRule);
					} catch (DataImportException e) {
						e.printStackTrace();
						failedCount++;
						importMessages.add("处理第"+correntRowIndex+"行，失败，"+e.getMessage());
						if(writeLog){
							ImportLogger.writeLog(loggerFile, uuid, "处理第"+correntRowIndex+"行，失败，"+e.getMessage());
						}
						return;
					}
				}
				
				if(sql1.toString().endsWith(",")){
					sql1.deleteCharAt(sql1.lastIndexOf(","));
				}
				if(sql2.toString().endsWith(",")){
					sql2.deleteCharAt(sql2.lastIndexOf(","));
				}
				String sql=sql1.append(sql2).append(sql3).toString();
				boolean b=false;
				try {
					DBAccess.excuteWithException(sql, null);
				} catch (Exception e) {
					e.printStackTrace();
					failedCount++;
					importMessages.add("处理第"+correntRowIndex+"行，失败，"+e.getMessage());
					if(writeLog){
						ImportLogger.writeLog(loggerFile, uuid, "处理第"+correntRowIndex+"行，失败，"+e.getMessage());
					}
					return;
				}
				successCount++;
				importMessages.add("处理第"+correntRowIndex+"行，成功");
				if(writeLog){
					ImportLogger.writeLog(loggerFile, uuid, "处理第"+correntRowIndex+"行，成功");
				}
			}
		}

		public void run() {
			try {
				if(sheetIndex<=0){
					this.processByRow();
				}else{
					this.processByRow(sheetIndex);
				}
				complete=true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void clearImporterMap(){
		Set<String> keySet=importerMap.keySet();
		Iterator<String> it=keySet.iterator();
		while(it.hasNext()){
			String uuid=it.next();
			ExcelImporter importer=importerMap.get(uuid);
			Thread processorThread=importer.getProcessorThread();
			if(!processorThread.isAlive()){
				importerMap.remove(uuid);
				importer.stop(uuid);
			}
		}
	}
	
	public static void startImport(String uuid,String fileName,String tableRuleId,boolean writeLog,String loggerFile){
		clearImporterMap();
		if(writeLog){
			ImportLogger.writeLog(loggerFile, uuid, "开始导入数据。");
		}
		try {
			ExcelImporter importer=new ExcelImporter(uuid,fileName,tableRuleId,writeLog,loggerFile);
			importer.importFirstSheetData();
			importerMap.put(uuid, importer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception {
		
	}
}


